import { isUndefined } from "@/utils"
import { http } from "../axios"
import { RequestOptions, ResponseBodyError, ResponseData } from "../types"

export interface FetchResult<T> {
    res: Ref<T | undefined>
    error: Ref<ResponseBodyError | undefined>
    isOk: () => boolean
}

export async function useFetch<T = any>(api: () => Promise<ResponseData<T>>): Promise<FetchResult<T>> {
    const responseRef = shallowRef<T>()
    const errorRef = shallowRef<ResponseBodyError>()

    try {
        const { data, status, message, code } = await api()
        if (status === true) {
            responseRef.value = data
            errorRef.value = undefined
        } else {
            responseRef.value = undefined
            errorRef.value = { name: "error", message, code }
        }
    } catch (e) {
        console.log("fetch error")
        responseRef.value = undefined
        errorRef.value = { name: "fetch error", message: "", cause: e }
    }

    const isOk = () => isUndefined(errorRef.value)
    return { res: responseRef, error: errorRef, isOk }
}

export const useGet = (url: string, params?: any, options?: RequestOptions) => useFetch(() => http.get(url, params, options))
export const usePost = (url: string, params?: any, options?: RequestOptions) => useFetch(() => http.post(url, params, options))
export const useDelete = (url: string, params?: any, options?: RequestOptions) => useFetch(() => http.delete(url, params, options))
export const usePut = (url: string, params?: any, options?: RequestOptions) => useFetch(() => http.put(url, params, options))
